import 'dart:io';
import 'dart:async';

Future<void> startHttpServer() async {
  final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
  print('Server started on port 8080');

  await for (HttpRequest request in server) {
    if (request.uri.path == '/upload' && request.method == 'POST') {
      // 处理文件上传
      final file = File('received_file.txt');
      final sink = file.openWrite();
      await request.pipe(sink);
      await sink.close();

      request.response.statusCode = HttpStatus.ok;
      request.response.write('File uploaded successfully');
      await request.response.close();
    } else if (request.uri.path == '/download' && request.method == 'GET') {
      // 处理文件下载
      final file = File('file_to_send.txt');
      if (await file.exists()) {
        request.response.headers.contentType = ContentType.binary;
        request.response.headers.add('Content-Disposition', 'attachment; filename=file_to_send.txt');
        await request.response.addStream(file.openRead());
      } else {
        request.response.statusCode = HttpStatus.notFound;
        request.response.write('File not found');
      }
      await request.response.close();
    } else {
      request.response.statusCode = HttpStatus.notFound;
      await request.response.close();
    }
  }
}